package com.zhuhjay.msm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import com.zhuhjay.msm.prop.MsmProperties;
import com.zhuhjay.msm.service.MsmService;
import com.zhuhjay.msm.utils.RandomUtil;
import com.zhuhjay.servicebase.exception.GuLiException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author ZhuHJay
 * @date 2022/9/8 10:11
 */
@Service
public class MsmServiceImpl implements MsmService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private MsmProperties properties;

    @Override
    public boolean send(String phone) {
        // 获取验证码
        String code = RandomUtil.getFourBitRandom();
        HashMap<String, String> map = new HashMap<>(1);
        map.put("code", code);
        DefaultProfile profile = DefaultProfile.getProfile(
                properties.getRegionId(),
                properties.getAccessKeyId(),
                properties.getSecret());

        IAcsClient client = new DefaultAcsClient(profile);

        //设置相关固定的参数
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");

        //设置发送相关的参数
        request.putQueryParameter("PhoneNumbers",phone);
        request.putQueryParameter("SignName",properties.getSignName());
        request.putQueryParameter("TemplateCode",properties.getTemplateCode());
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map));

        try {
            //最终发送
            CommonResponse response = client.getCommonResponse(request);
            if (response.getHttpResponse().isSuccess()) {
                redisTemplate.opsForValue().set(phone, code, 3, TimeUnit.MINUTES);
                return true;
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
